package com.yanqu.road.factory;

import com.yanqu.road.handle.ws.WSHandler;
import com.yanqu.road.utils.ConfigHelper;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleStateHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;

public class InitializerFactory {


    private static SSLContext createSslContext(String type, String path, String password) throws Exception {
        KeyStore ks = KeyStore.getInstance(type);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        ks.load(new FileInputStream(path), password.toCharArray());
        SSLContext sslContext = SSLContext.getInstance("TLS");
        kmf.init(ks, password.toCharArray());
        sslContext.init(kmf.getKeyManagers(), null, null);
        return sslContext;
    }


    public static void socketChannelInitialize(SocketChannel socketChannel, boolean isSsl) throws Exception{
        ChannelPipeline pipeline = socketChannel.pipeline();
        if(isSsl) {
            if (Boolean.valueOf(ConfigHelper.getValue("sslEnable"))) {
                SSLContext sslContext = createSslContext("JKS", ConfigHelper.getValue("sslPath"),
                        ConfigHelper.getValue("sslPass"));
                SSLEngine engine = sslContext.createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addLast(new SslHandler(engine));
            }
        }
        pipeline.addLast("idleState", new IdleStateHandler(30, 30, 30, TimeUnit.SECONDS));
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new WSHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    }



}
